package cn.bigcontainer.alt.meta.extension.impl;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import cn.bigcontainer.alt.common.util.WoJsonKit;
import cn.bigcontainer.alt.common.util.WoKit;
import cn.bigcontainer.alt.common.util.WoVelocityKit;
import cn.bigcontainer.alt.meta.dao.MDao;
import cn.bigcontainer.alt.meta.dto.MForm;
import cn.bigcontainer.alt.meta.dto.MViewDto;
import cn.bigcontainer.alt.meta.extension.MFormLoader;

/**
 * 默认表单加载扩展实现，允许在表单数据从数据库读取前后执行自定义sql.
 * 
 * @author jiaod
 *
 */
@Component(MFormLoader.DEFAULT)
public class SqlFormLoader implements MFormLoader {

	@Resource
	private WoVelocityKit velocity;

	@Resource
	private MDao dao;

	private MViewDto queryExtensionSql(MViewDto fv, Boolean create, Boolean before) {
		MForm app = (MForm) fv.getApp();
		String extension = app.getExtension(create ? MForm.PARAM_EXT_CREATE_LOAD : MForm.PARAM_EXT_UPDATE_LOAD);
		if (WoKit.isEmpty(extension)) {
			return null;
		}
		Map<String, String> extensionData = WoJsonKit.readAsType(extension, Map.class);
		String tmplString = extensionData.get(before ? "before" : "after");
		if (WoKit.isEmpty(tmplString)) {
			return null;
		}
		String sql = velocity.parse(tmplString, app.getObject().getRequest());
		Map<String, Object> map = dao.queryOne(sql);
		for (String key : map.keySet()) {
			fv.getProperties().forEach(fp -> {
				if (fp.getId().equals(key) || fp.getId().endsWith(key)) {
					fp.setValue(map.get(key));
				}
			});
		}
		return fv;
	}

	@Override
	public MViewDto before(MViewDto fv, String keyValue, Boolean create) {
		return queryExtensionSql(fv, create, true);
	}

	@Override
	public void after(MViewDto fv, String keyValue, Boolean create) {
		queryExtensionSql(fv, create, false);
	}

}
